package vin.pth.example.authrization.provider;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vin.pth.authorization.exception.AuthorizationException;
import vin.pth.authorization.provider.AuthorizationProvider;
import vin.pth.base.pojo.Authentication;
import vin.pth.base.pojo.UserDetails;
import vin.pth.base.service.UserDetailsService;
import vin.pth.example.authrization.token.SmsCodeToken;

/**
 * @author Cocoon
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class SmsCodeProvider implements AuthorizationProvider {

  private final static String DEFAULT_SMS_CODE = "123456";
  private final UserDetailsService userDetailsService;

  /**
   * 认证.
   *
   * @param authentication 认证对象
   * @return 认证结果
   * @throws AuthorizationException 鉴权异常
   */
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthorizationException {
    SmsCodeToken token = (SmsCodeToken) authentication;
    if (!token.getSmsCode().equals(DEFAULT_SMS_CODE)) {
      throw new AuthorizationException(401033,"验证码错误，请重新输入");
    }

    log.warn("短信验证码认证逻辑，默认直接通过");
    UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getPrincipal());
    if (userDetails == null) {
      throw new AuthorizationException(401404,"用户不存在");
    }
    return new SmsCodeToken(authentication.getPrincipal(), authentication.getCredentials(),
        userDetails);
  }

  /**
   * 是否支持该认证对象.
   *
   * @param authentication 认证对象.
   * @return 认证结果
   */
  @Override
  public boolean supports(Class<?> authentication) {
    return SmsCodeToken.class.isAssignableFrom(authentication);
  }
}
